package com.tongshu.miaosha.service;

import com.tongshu.miaosha.dao.GoodsDao;
import com.tongshu.miaosha.dao.OrderDao;
import com.tongshu.miaosha.domain.MiaoshaOrder;
import com.tongshu.miaosha.domain.MiaoshaUser;
import com.tongshu.miaosha.domain.OrderInfo;
import com.tongshu.miaosha.redis.OrderKey;
import com.tongshu.miaosha.utils.RedisUtil;
import com.tongshu.miaosha.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class OrderService {
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private RedisUtil redisUtil;

    // 通过查询redis缓存提速
    public MiaoshaOrder getMiaoshaOrderByUserIdGoodsId(Long userId, long goodsId) {
        return (MiaoshaOrder) redisUtil.get(OrderKey.getMiaoshaOrderByUidGid, "" + userId + "_" + goodsId);
    }

    @Transactional
    public OrderInfo createOrder(MiaoshaUser user, GoodsVo goodsVo) {
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setCreateDate(new Date());
        // 收获地址ID
        orderInfo.setDeliveryAddrId(0L);
        orderInfo.setGoodsCount(1);
        orderInfo.setGoodsId(goodsVo.getId());
        orderInfo.setGoodsName(goodsVo.getGoodsName());
        orderInfo.setGoodsPrice(goodsVo.getMiaoshaPrice());
        // 订单渠道 1pc，2android，3ios
        orderInfo.setOrderChannel(1);
        orderInfo.setStatus(0);
        orderInfo.setUserId(user.getId());
        orderDao.insertOrderInfo(orderInfo);
        long orderId = orderInfo.getId();

        MiaoshaOrder miaoshaOrder = new MiaoshaOrder();
        miaoshaOrder.setOrderId(orderId);
        miaoshaOrder.setGoodsId(goodsVo.getId());
        miaoshaOrder.setUserId(user.getId());
        orderDao.insert(miaoshaOrder);

        // 下单成功后将订单存入缓存，便于查找
        redisUtil.set(OrderKey.getMiaoshaOrderByUidGid, "" + user.getId() + "_" + goodsVo.getId(), miaoshaOrder);

        return orderInfo;
    }

    public OrderInfo getOrderById(long orderId) {
        return orderDao.getOrderById(orderId);
    }
}
